package cn.edu.hqu.cst.android.hxy.e3;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

public class ProgressDialogTest extends Activity {
    private int[] data = new int[100];
    int hasData = 0;
    final int PROGRESS_DIALOG = 0x112;
    int progressStatus = 0;
    ProgressDialog pd;

    Handler handler = new Handler(msg -> {
        if (msg.what == 0x123) {
            pd.setProgress(progressStatus);
        }
        return true;
    });

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_dialog);

        Button execBn = findViewById(R.id.exec);
        execBn.setOnClickListener(v -> showDialog(PROGRESS_DIALOG));
    }

    @Override
    public Dialog onCreateDialog(int id, Bundle status) {
        switch (id) {
            case PROGRESS_DIALOG:
                pd = new ProgressDialog(this);
                pd.setMax(100);
                pd.setTitle("任务完成百分比");
                pd.setMessage("耗时任务的完成百分比");
                pd.setCancelable(false);
                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pd.setIndeterminate(false);
                break;
        }
        return pd;
    }

    @Override
    public void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        switch (id) {
            case PROGRESS_DIALOG:
                pd.setProgress(0);
                new Thread(() -> {
                    while (progressStatus < 100) {
                        progressStatus = doWork();
                        if (progressStatus > 100) {
                            progressStatus = 100;
                        }
                        handler.sendEmptyMessage(0x123);
                    }
                    pd.dismiss();
                }).start();
                break;
        }
    }

    public synchronized int doWork() {
        if (hasData >= data.length) {
            return 100;
        }
        data[hasData++] = (int) (Math.random() * 100);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return (int) ((double) hasData / data.length * 100);
    }
}